#!/usr/bin/env python
# coding: utf-8
#####插件说明#####
# 自动根据币种调用查询接口进行指定模板回复
import json
import web
import re
import os
import requests
import time


def run(WXBOT, msg, plugin_name):
    try:
        WXBOT.bot_conf[plugin_name]
    except:
        WXBOT.bot_conf[plugin_name] = {
            'switch': False,  # 自动发消息功能开关
            'default_currency': "CNY",  # 默认货币
            'reply_templates': u"""coinmarketcap网\n币种：%s\n价格：￥%s\n24h涨幅：%s %%\n市值排名：%d\nCNY汇率：￥%s\n市值：￥%s\n更多：http://www.biben.com/\n【%s】"""
        }
        return

    # 连接数据库
    mysql_db = web.database(dbn="mysql", user='root', pw='root', db='wxbot', host='127.0.0.1')

    # 自动回复消息到群，联系人
    if WXBOT.bot_conf[plugin_name]['switch'] == True and ((msg['msg_type_id'] == 3 or msg['msg_type_id'] == 4)and msg['content']['type'] == 0):
        try:
            keywords = mysql_db.select("biben_coin_types")
            for x in keywords:
                if x['symbol'] == msg['content']['data'].upper():
                    # 找到消息,拼接消息并群内通知
                    # 默认货币
                    convert = {'convert': WXBOT.bot_conf[plugin_name]['default_currency']}
                    res = requests.get("https://api.coinmarketcap.com/v1/ticker/%s/" % (
                        x['slug']), params=convert)

                    send_message = WXBOT.bot_conf[plugin_name]['reply_templates'] % (
                        res.json()[0]['symbol'], res.json()[0]['price_cny'],
                        res.json()[0]['percent_change_24h'],
                        int(res.json()[0]['rank']), res.json()[0]['price_cny'], res.json()[0]['market_cap_cny'],
                        time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(res.json()[0]['last_updated']))))

                    WXBOT.send_msg_by_uid(send_message, msg['user']['id'])
                    # 打印输出发送日志
                    print u'[INFO] 消息发送成功，%s---->%s' % (msg['content']['data'], msg['user']['name'])
        except Exception, e:
            print u'[ERRO] 插件%s运行错误--->%s' % (__file__, e)